<script>
import {uploadFile} from "@/api/aihuman/common/minio";
import AiHumanWebRenderer from "@/views/aihuman/HumanAssets/actionType/aiHumanWebRenderer/test.vue";
import {getUrl} from "@/util/aihuman/getUrl";

export default {
  name: "BatchAddPage",
  components: {AiHumanWebRenderer},
  props: {
    title: {
      type: String,
      default: '新增资源包'
    },
    // web3d or ue
    type: {
      type: String,
      default: 'web3d'
    },
    // 1-动作；2-服饰
    dataType: {
      type: [String, Number],
      required: true
    },
    // upload file path
    fileFolderUrl: {
      type: String
    },
    // table title
    tableTitle: {
      type: String
    },
    previewType: {
      type: String,
      default: 'image'
    }
  },
  data() {
    return {
      submitLoading: false,
      isShow: false,
      loading: false,
      uploadLoading: false,
      mode: 'add',
      shotPicLoading: false,
      form: {
        name: '',
        fileUrl: ''
      },
      groupId: '',
      tableForm: {
        tableData: []
      },
      // glb's data
      uploadFileData: null,
      tableHeight: 100
    }
  },
  mounted() {
    this.calculateTableHeight();
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight);
  },
  methods: {
    getUrl,
    calculateTableHeight() {
      const containerHeight = document.documentElement.clientHeight

      const extraHeight = 380;

      this.tableHeight = containerHeight - extraHeight;
    },
    printCapture(row) {
      this.shotPicLoading = true
      let imgData = this.$refs.render.generatePicture()

      let file = this.dataURLtoFile(imgData, 'dress' + Date.now())

      this.uploadThumbnail(row, file)

      this.shotPicLoading = false
    },
    shortPic(row) {
      console.log(row);
      this.$refs.render.generateGif(row.id, (result) => {
        let file = this.dataURLtoFile(result, 'gif' + Date.now())
        console.log(file);
        this.uploadThumbnail(row, file)
      })
    },
    async uploadThumbnail(item, file) {
      let formData = new FormData()
      formData.append('file', file)
      formData.append('keyFolderPath', `${this.fileFolderUrl}${this.groupId}`)

      const {data} = await uploadFile(formData)
      item.previewImg = data.data.filePath
    },
    submitData() {
      this.submitLoading = true
      if (this.form.name === '') {
        this.$message.error('请输入资源包名称')
        this.submitLoading = false
        return false
      }

      let isPass = this.tableForm.tableData.every(el => {
        return el.id !== ''
      })

      if (!isPass) {
        this.$message.error('请完善表格内数据')
        this.submitLoading = false
        return false
      }

      this.$emit('submit', {
        pack: {
          ...this.form,
          ...{groupId: this.groupId},
          type: this.type === 'web3d' ? 3 : 4,
          fileFolderUrl: this.fileFolderUrl
        },
        list: this.tableForm.tableData
      })
    },
    addTable() {
      this.tableForm.tableData.push({
        name: '',
        id: '',
        second: '',
        previewImg: '',
        desc: [],
        tempDesc: '',
        inputVisible: false,
        // 唯一id
        uuid: ''
      })
    },
    removeRow(index) {
      this.tableForm.tableData.splice(index, 1)
    },
    open(group, mode = 'add', data = null) {
      this.isShow = true;
      this.groupId = group;
      this.mode = mode;
      if (mode === 'add') {
        this.form.fileUrl = ''
        this.form.name = ''
        this.tableForm.tableData = []

      } else if (mode === 'preview') {
        this.form = data.form;
        this.tableForm.tableData = data.list
      } else {
        this.form = data.form;
        this.tableForm.tableData = data.list
      }
    },
    close() {
      this.isShow = false
    },
    /**
     * upload glb
     * @param file
     * @returns {Promise<void>}
     */
    async uploadActionFile(file) {
      console.log(file.file);
      this.loading = true
      let formData = new FormData()
      formData.append('file', file.file)
      formData.append('keyFolderPath', `${this.fileFolderUrl}${this.groupId}`)
      const {data} = await uploadFile(formData)
      this.form.fileUrl = data.data.filePath
      this.form.name = data.data.oldFileNameWithoutExtension
      this.uploadFileData = data.data
      this.loading = false
    },
    async uploadImg(file, row) {
      this.uploadLoading = true
      if (this.dataType === 1 && file.file.type !== 'video/webm') {
        this.$message.error('请上传webm文件')
        this.uploadLoading = false
        return false
      }
      if (this.dataType === 2 && !['image/jpeg', 'image/png', 'image/jpg'].includes(file.file.type)) {

        this.$message.error('请上传jpg或者png文件')
        this.uploadLoading = false
        return false
      }

      let formData = new FormData()
      formData.append('file', file.file)
      formData.append('keyFolderPath', `${this.fileFolderUrl}${this.groupId}`)
      const {data} = await uploadFile(formData)
      row.previewImg = data.data.filePath
      this.uploadLoading = false
    },
    dataURLtoFile(base64String, fileName) {
      // 检查 Base64 格式，提取 MIME 类型
      const matches = base64String.match(/^data:(.*?);base64,/);
      if (!matches) {
        throw new Error("Invalid Base64 format");
      }
      const mimeType = matches[1]; // 提取 MIME 类型

      // 去掉前缀，保留纯 Base64 数据部分
      const base64Data = base64String.split(",")[1];

      // 解码 Base64 数据
      const byteCharacters = atob(base64Data);

      // 将 Base64 转为二进制字节数组
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);

      // 根据解析的 MIME 类型动态设置文件扩展名
      const extension = mimeType.split("/")[1] || "file";
      const finalFileName = `${fileName}.${extension}`;

      // 创建 File 对象
      return new File([byteArray], finalFileName, {type: mimeType});
    },
    /**
     * 上传glb后数据操作
     * @param data
     */
    getAnimateData(data) {
      console.log(data);
      if (this.mode !== 'add') {
        return false
      }
      if (this.dataType === 1) {
        this.tableForm.tableData = data.map(el => {
          return {
            name: el.name,
            id: el.name,
            second: el.duration.toFixed(3),
            previewImg: '',
            desc: [],
            tempDesc: '',
            inputVisible: false,
            uuid: '',
            ...el
          }
        })
      } else {
        // 服饰
        this.tableForm.tableData = [{
          name: this.form.name,
          id: Date.now(),
          second: '',
          desc: [],
          tempDesc: '',
          inputVisible: false,
          previewImg: '',
          uuid: ''
        }]
      }
    },
    playVideo(e) {
      console.log(e);
      e.target.loop = true
      e.target.play()
    },
    pauseVideo(e) {
      e.target.loop = false
      e.target.pause()
    },
    showPopVideo() {
    },
    handleClose(list, tag) {
      list.splice(list.indexOf(tag), 1);
    },
    handleInputConfirm(row) {
      let inputValue = row.tempDesc;

      if (inputValue.length > 10) {
        this.$message.error('动作含义字数最长为10个')
        return false
      }

      if (inputValue.length > 0 && row.desc.indexOf(inputValue) !== -1) {
        this.$message.error('动作含义已存在，请修改')
        return false
      }

      if (inputValue) {
        row.desc.push(inputValue);
      }
      row.inputVisible = false;
      row.tempDesc = '';
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  }
}
</script>

<template>
  <div v-if="isShow" class="batch-add-page">
    <header>
      <strong>
        {{ title }}
      </strong>
    </header>
    <div class="batch-form-item">
      <el-form ref="form" :model="form" :disabled="mode === 'preview'" inline label-width="auto" size="small">
        <el-form-item v-if="type === 'web3d'">
          <el-upload
            v-if="form.fileUrl === ''"
            action=""
            ref="uploadRef"
            :http-request="uploadActionFile"
            :show-file-list="false"
            :disabled="loading"
            style="width: 100%;"
          >
            <el-button size="small" type="primary" :loading="loading">上传glb模型</el-button>
          </el-upload>

          <ai-human-web-renderer
            v-else
            ref="render"
            :url="`${getUrl()}/${form.fileUrl}`"
            width="100"
            height="150"
            @onLoaded="getAnimateData"
          />
        </el-form-item>
        <el-form-item label="资源包名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="资源包路径">
          <el-input v-model="form.fileUrl" :title="form.fileUrl" :disabled="type === 'web3d'"></el-input>
        </el-form-item>

        <!--        <el-form-item label="资源包id">
                </el-form-item>-->

        <el-form-item label="类型">
          {{ type === 'web3d' ? 'Web3D' : 'UE3D' }}
        </el-form-item>

      </el-form>
    </div>

    <div>
      <header class="table-header">
        <h5>{{ tableTitle }}</h5>
        <el-button
          v-if="mode !== 'preview' && type === 'ue'"
          type="primary" size="small" icon="el-icon-plus"
          @click="addTable">新增
        </el-button>
      </header>
      <el-form v-model="tableForm" inline-message :disabled="mode === 'preview'">
        <el-table
          :data="tableForm.tableData"
          border
          :height="tableHeight"
          style="width: 100%">
          <el-table-column
            prop="date"
            :label="dataType === 1 ? '动作名称': '服饰名称'"
            min-width="180">
            <template #default="{row, $index}">
              <el-form-item :key="$index">
                <el-input v-model="row.name"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            prop="date"
            :label="dataType === 1 ? '动作ID': '服饰ID'"
            min-width="180">
            <template #default="{row, $index}">
              <el-form-item :key="$index">
                <el-input v-model="row.id" :disabled="type === 'Web3d'"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            v-if="dataType === 1"
            prop="date"
            label="动作时长"
            min-width="180">
            <template #default="{row, $index}">
              <el-form-item :key="$index">
                <el-input v-model="row.second" :disabled="type === 'Web3d'"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            prop="date"
            label="预览"
            min-width="180">
            <template v-slot="{row}">
              <el-form-item>
                <div class="table-btn">
                  <el-upload
                    class=""
                    action=""
                    v-loading="uploadLoading"
                    :show-file-list="false"
                    :http-request="params => uploadImg(params,row)"
                  >
                    <el-button size="small" type="text">上传</el-button>
                  </el-upload>
                  <!-- web3d 动作类别上传视频-->
                  <!-- <el-button
                          v-if="type === 'web3d' && dataType === 1"
                          type="text"
                          @click="shortPic(row)">
                          截图
                        </el-button>-->
                  <el-button
                    v-if="type === 'web3d' && dataType === 2"
                    type="text"
                    @click="printCapture(row)">
                    截图
                  </el-button>
                </div>

                <div>
                  <template v-if="previewType === 'image'">
                    <el-popover
                      placement="left"
                      title=""
                      width="200"
                      trigger="hover"
                    >
                      <img
                        v-if="row.previewImg"
                        :src="`${getUrl()}${row.previewImg}`" alt=""
                        style="height: 200px; width: 200px; object-fit: contain">
                      <div slot="reference">
                        <img
                          v-if="row.previewImg"
                          :src="`${getUrl()}${row.previewImg}`" alt=""
                          style="height: 80px; width: 80px; object-fit: contain">
                      </div>
                    </el-popover>
                  </template>

                  <template v-if="previewType === 'video'">
                    <el-popover
                      placement="left"
                      title=""
                      width="200"
                      trigger="hover"
                      @show="showPopVideo"
                    >
                      <video
                        v-if="row.previewImg"
                        :src="`${getUrl()}` + row.previewImg || ''"
                        style="width: 200px; height: 150px; display: block"
                        muted
                        autoplay
                        loop
                      >
                      </video>
                      <div slot="reference">
                        <video
                          v-if="row.previewImg"
                          :src="`${getUrl()}` + row.previewImg || ''"
                          style="width: 100px; height: 150px; display: block"
                          muted
                        >
                        </video>
                      </div>
                    </el-popover>
                  </template>
                </div>

              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            v-if="dataType === 1"
            prop="desc"
            label="动作含义"
            min-width="180">
            <template #default="{row, $index}">
              <el-form-item :key="$index">
                <!--                <el-input v-model="row.desc"></el-input>-->

                <el-tag
                  :key="tag"
                  v-for="tag in row.desc"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(row.desc, tag)">
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.tempDesc"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">新增</el-button>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            v-if="mode !== 'preview' && type === 'ue'"
            prop=""
            width="180"
            align="center"
            label="操作"
          >
            <template #default="{row, $index}">
              <el-button type="text" icon="el-icon-delete" @click="removeRow($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <div class="page-footer">
      <el-button @click="close" :loading="submitLoading">取消</el-button>
      <el-button v-if="mode !== 'preview'" type="primary" :loading="submitLoading" @click="submitData">确认</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.table-btn {
  align-items: center;
  display: flex;
}

.page-footer {
  display: flex;
  justify-content: flex-end;
  height: 50px;
  align-items: center;
}

.table-header {
  display: flex;
  align-items: center;
  height: 40px;
  justify-content: space-between;
}

.batch-form-item {
  padding: 15px 0;
}

.batch-add-page {
  background: #fff;
  position: absolute;
  border-radius: 20px;
  overflow: auto;
  padding: 20px;
  left: 30px;
  top: 62px;
  bottom: 30px;
  right: 30px;
  z-index: 100;
}
</style>
